package com.insight.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.constant.CommonConstant;
import com.insight.common.message.websocket.WebSocket;
import com.insight.common.system.vo.LoginUser;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.SysAnnouncement;
import com.insight.modules.system.entity.SysAnnouncementSend;
import com.insight.modules.system.model.AnnouncementSendModel;
import com.insight.modules.system.service.ISysAnnouncementSendService;
import com.insight.modules.system.service.ISysAnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * 用户通告阅读标记表控制器
 * 提供用户通告阅读标记的增删改查及阅读状态更新等接口
 *
 * @author jeecg-boot
 * @date 2019-02-21
 * @version V1.0
 */
@RestController
@RequestMapping("/sys/sysAnnouncementSend")
@Slf4j
public class SysAnnouncementSendController {
	@Autowired
	private ISysAnnouncementSendService sysAnnouncementSendService;

	@Autowired
	private ISysAnnouncementService sysAnnouncementService;

	/**
	 * 分页列表查询用户通告阅读标记
	 *
	 * @param sysAnnouncementSend 查询条件实体
	 * @param pageNo 页码，默认1
	 * @param pageSize 每页条数，默认10
	 * @param req Http请求对象，用于获取排序参数
	 * @return 分页结果封装对象
	 */
	@GetMapping(value = "/list")
	public Result<IPage<SysAnnouncementSend>> queryPageList(SysAnnouncementSend sysAnnouncementSend,
															@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															HttpServletRequest req) {
		Result<IPage<SysAnnouncementSend>> result = new Result<>();
		// 根据实体创建查询包装器
		QueryWrapper<SysAnnouncementSend> queryWrapper = new QueryWrapper<>(sysAnnouncementSend);
		Page<SysAnnouncementSend> page = new Page<>(pageNo,pageSize);
		// 排序逻辑处理：根据请求参数column和order决定排序方式
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		if(oConvertUtils.isNotEmpty(column) && oConvertUtils.isNotEmpty(order)) {
			if("asc".equals(order)) {
				queryWrapper.orderByAsc(oConvertUtils.camelToUnderline(column));
			} else {
				queryWrapper.orderByDesc(oConvertUtils.camelToUnderline(column));
			}
		}
		// 执行分页查询
		IPage<SysAnnouncementSend> pageList = sysAnnouncementSendService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	/**
	 * 添加新的用户通告阅读标记
	 *
	 * @param sysAnnouncementSend 实体对象
	 * @return 操作结果封装
	 */
	@PostMapping(value = "/add")
	public Result<SysAnnouncementSend> add(@RequestBody SysAnnouncementSend sysAnnouncementSend) {
		Result<SysAnnouncementSend> result = new Result<SysAnnouncementSend>();
		try {
			if (sysAnnouncementSend == null) {
				return result.error500("请求参数为空");
			}
			sysAnnouncementSendService.save(sysAnnouncementSend);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	 * 编辑用户通告阅读标记
	 *
	 * @param sysAnnouncementSend 带有修改信息的实体对象
	 * @return 操作结果封装
	 */
	@PutMapping(value = "/edit")
	public Result<SysAnnouncementSend> eidt(@RequestBody SysAnnouncementSend sysAnnouncementSend) {
		Result<SysAnnouncementSend> result = new Result<>();
		// 根据ID查询实体是否存在
		SysAnnouncementSend sysAnnouncementSendEntity = sysAnnouncementSendService.getById(sysAnnouncementSend.getId());
		if(sysAnnouncementSendEntity == null) {
			result.error500("未找到对应实体");
		} else {
			// 更新实体数据
			boolean ok = sysAnnouncementSendService.updateById(sysAnnouncementSend);
			// 返回true表示更新成功
			if(ok) {
				result.success("修改成功!");
			}
		}
		return result;
	}

	/**
	 * 通过ID删除用户通告阅读标记
	 *
	 * @param id 主键ID
	 * @return 操作结果封装
	 */
	@DeleteMapping(value = "/delete")
	public Result<SysAnnouncementSend> delete(@RequestParam(name="id",required=true) String id) {
		Result<SysAnnouncementSend> result = new Result<>();
		// 先查询是否存在
		SysAnnouncementSend sysAnnouncementSend = sysAnnouncementSendService.getById(id);
		if(sysAnnouncementSend == null) {
			result.error500("未找到对应实体");
		} else {
			// 存在则删除
			boolean ok = sysAnnouncementSendService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}
		return result;
	}

	/**
	 * 批量删除用户通告阅读标记
	 *
	 * @param ids 多个ID以逗号分隔
	 * @return 操作结果封装
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<SysAnnouncementSend> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<SysAnnouncementSend> result = new Result<>();
		if(ids == null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		} else {
			// 拆分ID字符串为集合后批量删除
			this.sysAnnouncementSendService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	 * 根据ID查询用户通告阅读标记
	 *
	 * @param id 主键ID
	 * @return 查询结果封装
	 */
	@GetMapping(value = "/queryById")
	public Result<SysAnnouncementSend> queryById(@RequestParam(name="id",required=true) String id) {
		Result<SysAnnouncementSend> result = new Result<>();
		SysAnnouncementSend sysAnnouncementSend = sysAnnouncementSendService.getById(id);
		if(sysAnnouncementSend == null) {
			result.error500("未找到对应实体");
		} else {
			result.setResult(sysAnnouncementSend);
			result.setSuccess(true);
		}
		return result;
	}

	/**
	 * 根据通告ID和当前用户ID，更新阅读状态为已读
	 *
	 * @param json JSON对象，包含anntId字段（通告ID）
	 * @return 操作结果封装
	 */
	@PutMapping(value = "/editByAnntIdAndUserId")
	public Result<SysAnnouncementSend> editById(@RequestBody JSONObject json) {
		Result<SysAnnouncementSend> result = new Result<>();
		String anntId = json.getString("anntId");
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();

		// 构造更新条件，设置阅读标记和阅读时间
		LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper<SysAnnouncementSend>().lambda();
		updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG);
		updateWrapper.set(SysAnnouncementSend::getReadTime, new Date());
		updateWrapper.eq(SysAnnouncementSend::getAnntId, anntId);
		updateWrapper.eq(SysAnnouncementSend::getUserId, userId);

		// 执行更新
		SysAnnouncementSend announcementSend = new SysAnnouncementSend();
		sysAnnouncementSendService.update(announcementSend, updateWrapper);

		// 查询通告消息
		SysAnnouncement announcement = sysAnnouncementService.getById(anntId);
		JSONObject data = new JSONObject();
		data.put("id", anntId);
		data.put("msgCategory", announcement.getMsgCategory());
		JSONObject jsonOut = new JSONObject();
		jsonOut.put("messageType", "clearNotice");
		jsonOut.put("data", data);
		// 发送websocket消息给当前用户，通知清除未读提醒
		WebSocket.sendOneMessage(userId, jsonOut.toJSONString());

		result.setSuccess(true);
		return result;
	}

	/**
	 * 获取当前登录用户的消息列表（分页）
	 *
	 * @param announcementSendModel 查询参数封装实体
	 * @param pageNo 页码，默认1
	 * @param pageSize 每页数量，默认10
	 * @return 分页消息列表
	 */
	@AutoLog(value = "获取我的消息")
	@GetMapping(value = "/getMyAnnouncementSend")
	public Result<IPage<AnnouncementSendModel>> getMyAnnouncementSend(AnnouncementSendModel announcementSendModel,
																	  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																	  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		Result<IPage<AnnouncementSendModel>> result = new Result<>();
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		announcementSendModel.setUserId(userId);
		announcementSendModel.setPageNo((pageNo - 1) * pageSize);
		announcementSendModel.setPageSize(pageSize);

		Page<AnnouncementSendModel> pageList = new Page<>(pageNo,pageSize);
		pageList = sysAnnouncementSendService.getMyAnnouncementSendPage(pageList, announcementSendModel);

		result.setResult(pageList);
		result.setSuccess(true);
		return result;
	}

	/**
	 * 一键已读，将当前登录用户的所有通告消息标记为已读
	 *
	 * @return 操作结果封装
	 */
	@AutoLog(value = "一键已读")
	@PutMapping(value = "/readAll")
	public Result<SysAnnouncementSend> readAll() {
		Result<SysAnnouncementSend> result = new Result<>();
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();

		// 构造更新条件，将当前用户所有通告阅读标记设为已读，更新时间为当前时间
		LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper<SysAnnouncementSend>().lambda();
		updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG);
		updateWrapper.set(SysAnnouncementSend::getReadTime, new Date());
		updateWrapper.eq(SysAnnouncementSend::getUserId, userId);

		SysAnnouncementSend announcementSend = new SysAnnouncementSend();
		sysAnnouncementSendService.update(announcementSend, updateWrapper);

		result.setSuccess(true);
		result.setMessage("全部已读");

		// 发送websocket消息通知前端清除未读提醒
		JSONObject jsonOut = new JSONObject();
		jsonOut.put("messageType", "clearNotice");
		WebSocket.sendOneMessage(userId, jsonOut.toJSONString());

		return result;
	}
}

